<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <title>个人中心 - 音乐服务器</title>

    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入动画库 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" rel="stylesheet">

    <!-- 配置Tailwind自定义主题 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            DEFAULT: '#6366f1',
                            light: '#8183f4',
                            dark: '#4f46e5'
                        },
                        secondary: {
                            DEFAULT: '#8b5cf6',
                            light: '#a37cf8',
                            dark: '#7c3aed'
                        },
                        dark: {
                            DEFAULT: '#1e293b',
                            light: '#334155',
                            lighter: '#475569'
                        },
                        light: {
                            DEFAULT: '#f8fafc',
                            dark: '#f1f5f9'
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    animation: {
                        'fade-in': 'fadeIn 0.5s ease-in-out',
                        'slide-up': 'slideUp 0.3s ease-out'
                    }
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .bg-gradient-profile {
                background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            }

            .bg-gradient-dark {
                background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
            }

            .card-shadow {
                box-shadow: 0 10px 25px -5px rgba(99, 102, 241, 0.1), 0 8px 10px -6px rgba(99, 102, 241, 0.1);
            }

            .input-focus {
                @apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none transition-all;
            }

            .btn-hover-effect {
                @apply hover:shadow-md hover:shadow-primary/20 active:scale-[0.98] transition-all;
            }

            .glass-effect {
                background: rgba(255, 255, 255, 0.1);
                backdrop-filter: blur(10px);
                -webkit-backdrop-filter: blur(10px);
            }

            .pagination-btn {
                @apply w-8 h-8 flex items-center justify-center rounded-full border border-gray-300 text-sm font-medium transition-all;
            }

            .pagination-btn.active {
                @apply bg-primary text-white border-primary;
            }

            .pagination-btn:not(.active):hover {
                @apply bg-gray-100;
            }

            .pagination-btn.disabled {
                @apply opacity-50 cursor-not-allowed;
            }

            @keyframes slideUp {
                from {
                    opacity: 0;
                    transform: translateY(20px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            .animate-slide-up {
                animation: slideUp 0.3s ease-out;
            }
        }
    </style>
</head>
<body class="font-inter bg-light min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm sticky top-0 z-50 glass-effect">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-3">
            <div class="w-10 h-10 rounded-full bg-gradient-profile flex items-center justify-center text-white shadow-md">
                <i class="fa fa-music"></i>
            </div>
            <h1 class="text-xl font-bold text-dark">音乐服务器</h1>
        </div>

        <div class="flex items-center space-x-4">
            <a href="list.html" class="text-dark/80 hover:text-primary transition-colors flex items-center group">
                <i class="fa fa-home mr-2 group-hover:scale-110 transition-transform"></i>
                <span class="hidden sm:inline">音乐首页</span>
            </a>
            <a href="loveMusic.html" class="text-dark/80 hover:text-primary transition-colors flex items-center group">
                <i class="fa fa-heart mr-2 group-hover:scale-110 transition-transform"></i>
                <span class="hidden sm:inline">喜欢列表</span>
            </a>
            <a href="upload.html" class="text-dark/80 hover:text-primary transition-colors flex items-center group">
                <i class="fa fa-cloud-upload mr-2 group-hover:scale-110 transition-transform"></i>
                <span class="hidden sm:inline">上传音乐</span>
            </a>
            <button id="logoutBtn" class="text-dark/80 hover:text-red-500 transition-colors flex items-center group">
                <i class="fa fa-sign-out mr-2 group-hover:scale-110 transition-transform"></i>
                <span class="hidden sm:inline">退出登录</span>
            </button>
        </div>
    </div>
</header>

<!-- 主要内容区 -->
<main class="flex-grow container mx-auto px-4 py-8 animate-fade-in">
    <div class="max-w-6xl mx-auto">
        <!-- 简约个人资料卡片 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden mb-8 card-shadow animate-slide-up">
            <div class="px-6 md:px-8 py-8">
                <div class="flex flex-col md:flex-row">
                    <div class="flex justify-center md:justify-start relative group">
                        <div class="w-32 h-32 rounded-full bg-white border-4 border-white overflow-hidden shadow-lg relative">
                            <img src="https://source.unsplash.com/random/300x300/?portrait"
                                 alt="用户头像"
                                 class="w-full h-full object-cover"
                                 id="userAvatar">
                            <div class="absolute inset-0 bg-black/30 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                <button id="changeAvatar"
                                        class="text-white bg-black/50 rounded-full p-2 hover:bg-black/70 transition-colors">
                                    <i class="fa fa-camera"></i>
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 用户名和操作 -->
                    <div class="mt-6 md:mt-0 md:ml-8 flex-grow">
                        <div class="flex flex-col md:flex-row md:items-end justify-between">
                            <div>
                                <h2 class="text-3xl font-bold text-dark" id="nickname">音乐爱好者</h2>
                                <p class="text-gray-500 mt-1 flex items-center">
                                    <i class="fa fa-envelope mr-2"></i>
                                    <span id="userEmail">user@example.com</span>
                                </p>
                            </div>
                            <div class="flex space-x-3 mt-4 md:mt-0">
                                <button id="editProfile"
                                        class="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-lg btn-hover-effect flex items-center">
                                    <i class="fa fa-pencil mr-2"></i>编辑资料
                                </button>
                                <button id="changePassword"
                                        class="bg-secondary hover:bg-secondary-dark text-white px-5 py-2.5 rounded-lg btn-hover-effect flex items-center">
                                    <i class="fa fa-lock mr-2"></i>修改密码
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 卡片式统计信息 -->
                <div class="mt-8 grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div class="bg-light/50 rounded-lg p-6 hover:shadow-md transition-shadow">
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-4">
                                <i class="fa fa-heart text-xl"></i>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-dark" id="statsFavorites">0</div>
                                <div class="text-sm text-gray-500">收藏歌曲</div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-light/50 rounded-lg p-6 hover:shadow-md transition-shadow">
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-4">
                                <i class="fa fa-cloud-upload text-xl"></i>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-dark" id="statsUploads">0</div>
                                <div class="text-sm text-gray-500">上传音乐</div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-light/50 rounded-lg p-6 hover:shadow-md transition-shadow">
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-4">
                                <i class="fa fa-play-circle text-xl"></i>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-dark" id="statsPlays">0</div>
                                <div class="text-sm text-gray-500">播放次数</div>
                            </div>
                        </div>
                    </div>
                    <div class="bg-light/50 rounded-lg p-6 hover:shadow-md transition-shadow">
                        <div class="flex items-center">
                            <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-4">
                                <i class="fa fa-list-ul text-xl"></i>
                            </div>
                            <div>
                                <div class="text-2xl font-bold text-dark" id="statsPlaylists">0</div>
                                <div class="text-sm text-gray-500">创建歌单</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 内容标签页 -->
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
            <div class="border-b border-gray-200 w-full md:w-auto mb-4 md:mb-0">
                <nav class="-mb-px flex space-x-8">
                    <button class="profile-tab-active whitespace-nowrap py-3 px-1 border-b-2 border-primary text-primary font-medium flex items-center">
                        <i class="fa fa-cloud-upload mr-2"></i>我的上传
                    </button>
                    <button class="profile-tab whitespace-nowrap py-3 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 flex items-center">
                        <i class="fa fa-history mr-2"></i>最近播放
                    </button>
                    <button class="profile-tab whitespace-nowrap py-3 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 flex items-center">
                        <i class="fa fa-heart mr-2"></i>我的收藏
                    </button>
                    <button class="profile-tab whitespace-nowrap py-3 px-1 border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 flex items-center">
                        <i class="fa fa-cog mr-2"></i>账户设置
                    </button>
                </nav>
            </div>
            <div class="relative w-full md:w-auto">
                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="fa fa-search text-gray-400"></i>
                </div>
                <input type="text" id="searchMusic"
                       class="block w-full md:w-64 pl-10 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary input-focus"
                       placeholder="搜索我的音乐...">
            </div>
        </div>

        <!-- 我的上传列表 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden card-shadow animate-slide-up">
            <div class="p-6 md:p-8">
                <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
                    <h3 class="text-xl font-bold text-dark flex items-center">
                        <i class="fa fa-cloud-upload mr-2 text-primary"></i>我上传的音乐
                    </h3>
                    <div class="mt-3 md:mt-0 flex space-x-2">
                        <button id="sortByName"
                                class="text-gray-500 hover:text-primary transition-colors flex items-center text-sm">
                            <i class="fa fa-sort-alpha-asc mr-1"></i>按名称
                        </button>
                        <button id="sortByDate"
                                class="text-gray-500 hover:text-primary transition-colors flex items-center text-sm">
                            <i class="fa fa-calendar mr-1"></i>按日期
                        </button>
                        <button id="refreshList"
                                class="text-gray-500 hover:text-primary transition-colors flex items-center text-sm">
                            <i class="fa fa-refresh mr-1"></i>刷新
                        </button>
                    </div>
                </div>

                <!-- 列表头部 -->
                <div class="hidden md:grid grid-cols-12 gap-4 text-sm font-medium text-gray-500 uppercase mb-4 pb-2 border-b border-gray-100">
                    <div class="col-span-5 flex items-center">
                        <span>歌曲名</span>
                        <button class="ml-2 text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-sort"></i>
                        </button>
                    </div>
                    <div class="col-span-3 flex items-center">
                        <span>歌手</span>
                        <button class="ml-2 text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-sort"></i>
                        </button>
                    </div>
                    <div class="col-span-2 flex items-center">
                        <span>上传时间</span>
                        <button class="ml-2 text-gray-400 hover:text-primary transition-colors">
                            <i class="fa fa-sort"></i>
                        </button>
                    </div>
                    <div class="col-span-2">操作</div>
                </div>

                <!-- 上传列表 (通过JS动态加载) -->
                <div id="uploadedList" class="divide-y divide-gray-100">
                    <!-- 示例项将通过JS动态生成 -->
                </div>

                <!-- 加载状态 -->
                <div id="loadingState" class="py-12 flex justify-center">
                    <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary"></div>
                </div>

                <!-- 空状态 -->
                <div id="uploadEmptyState" class="hidden py-16 text-center">
                    <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-light text-primary mb-4">
                        <i class="fa fa-cloud-upload text-2xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-dark mb-1">暂无上传的音乐</h3>
                    <p class="text-gray-500 max-w-md mx-auto">去上传一些音乐分享给大家吧</p>
                    <button class="mt-4 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-lg btn-hover-effect"
                            onclick="window.location.href='upload.html'">
                        <i class="fa fa-upload mr-2"></i>上传音乐
                    </button>
                </div>

                <!-- 分页 -->
                <div id="pagination" class="mt-6 flex items-center justify-center pt-4 hidden">
                    <div class="flex items-center space-x-1">
                        <button id="prevPage" class="pagination-btn disabled">
                            <i class="fa fa-chevron-left"></i>
                        </button>

                        <div id="pageNumbers" class="flex items-center space-x-1 mx-2">
                            <!-- 页码将通过JS动态生成 -->
                        </div>

                        <button id="nextPage" class="pagination-btn">
                            <i class="fa fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-dark text-white py-8 mt-12">
    <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
                <h3 class="text-lg font-bold mb-4 flex items-center">
                    <div class="w-8 h-8 rounded-full bg-primary flex items-center justify-center mr-2">
                        <i class="fa fa-music"></i>
                    </div>
                    音乐服务器
                </h3>
                <p class="text-gray-300 text-sm">发现和分享你喜爱的音乐</p>
            </div>
            <div>
                <h4 class="text-md font-semibold mb-3">探索</h4>
                <ul class="space-y-2 text-sm text-gray-300">
                    <li><a href="#" class="hover:text-primary transition-colors">热门音乐</a></li>
                    <li><a href="#" class="hover:text-primary transition-colors">最新发布</a></li>
                    <li><a href="#" class="hover:text-primary transition-colors">音乐分类</a></li>
                    <li><a href="#" class="hover:text-primary transition-colors">艺术家</a></li>
                </ul>
            </div>
            <div>
                <h4 class="text-md font-semibold mb-3">关于</h4>
                <ul class="space-y-2 text-sm text-gray-300">
                    <li><a href="#" class="hover:text-primary transition-colors">关于我们</a></li>
                    <li><a href="#" class="hover:text-primary transition-colors">服务条款</a></li>
                    <li><a href="#" class="hover:text-primary transition-colors">隐私政策</a></li>
                    <li><a href="#" class="hover:text-primary transition-colors">帮助中心</a></li>
                </ul>
            </div>
            <div>
                <h4 class="text-md font-semibold mb-3">联系我们</h4>
                <ul class="space-y-2 text-sm text-gray-300">
                    <li class="flex items-center"><i class="fa fa-envelope mr-2"></i> support@music-server.com</li>
                    <li class="flex items-center"><i class="fa fa-phone mr-2"></i>19178715445</li>
                    <li class="flex items-center"><i class="fa fa-map-marker mr-2"></i>广西钦州</li>
                </ul>
                <div class="mt-4 flex space-x-4">
                    <a href="#" class="text-gray-300 hover:text-primary transition-colors">
                        <i class="fa fa-weixin"></i>
                    </a>
                    <a href="#" class="text-gray-300 hover:text-primary transition-colors">
                        <i class="fa fa-weibo"></i>
                    </a>
                    <a href="#" class="text-gray-300 hover:text-primary transition-colors">
                        <i class="fa fa-github"></i>
                    </a>
                </div>
            </div>
        </div>
        <div class="border-t border-gray-700 mt-8 pt-6 text-center text-sm text-gray-400">
            <p>&copy; 2025 音乐服务器. 保留所有权利.</p>
        </div>
    </div>
</footer>

<!-- 音乐播放器 -->
<div id="musicPlayer"
     class="fixed bottom-0 left-0 right-0 bg-white shadow-lg z-50 transform translate-y-full transition-transform duration-300 ease-in-out">
    <div class="container mx-auto px-4">
        <div class="flex items-center justify-between py-3">
            <div class="flex items-center space-x-4 w-1/3">
                <div class="w-12 h-12 rounded bg-gray-200 flex-shrink-0 overflow-hidden">
                    <img id="playerCover" src="https://source.unsplash.com/random/100x100/?music" alt="封面"
                         class="w-full h-full object-cover">
                </div>
                <div>
                    <h4 id="playerTitle" class="font-medium text-dark truncate">歌曲名称</h4>
                    <p id="playerArtist" class="text-sm text-gray-500">歌手名称</p>
                </div>
            </div>

            <div class="flex flex-col items-center w-1/3">
                <div class="flex items-center space-x-4 mb-2">
                    <button id="prevBtn" class="text-gray-600 hover:text-primary transition-colors">
                        <i class="fa fa-step-backward"></i>
                    </button>
                    <button id="playBtn"
                            class="w-10 h-10 flex items-center justify-center rounded-full bg-primary text-white hover:bg-primary-dark">
                        <i class="fa fa-play" id="playIcon"></i>
                    </button>
                    <button id="nextBtn" class="text-gray-600 hover:text-primary transition-colors">
                        <i class="fa fa-step-forward"></i>
                    </button>
                </div>
                <div class="w-full flex items-center space-x-3">
                    <span id="currentTime" class="text-xs text-gray-500">0:00</span>
                    <div class="flex-grow h-1.5 bg-gray-200 rounded-full overflow-hidden">
                        <div id="progressBar" class="bg-primary h-full rounded-full" style="width: 0%"></div>
                    </div>
                    <span id="totalTime" class="text-xs text-gray-500">3:45</span>
                </div>
            </div>

            <div class="flex items-center justify-end space-x-3 w-1/3">
                <button id="volumeBtn" class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-volume-up"></i>
                </button>
                <div id="volumeControl" class="w-24 h-1.5 bg-gray-200 rounded-full overflow-hidden hidden">
                    <div id="volumeBar" class="bg-primary h-full rounded-full" style="width: 80%"></div>
                </div>
                <button id="playlistBtn" class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-list"></i>
                </button>
                <button id="closePlayer" class="text-gray-600 hover:text-red-500 transition-colors">
                    <i class="fa fa-times"></i>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 头像上传模态框（修改后，添加加载状态） -->
<div id="avatarModal" class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50"></div>
    <div class="relative max-w-md mx-auto my-12 bg-white rounded-lg shadow-xl overflow-hidden animate-slide-up">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-dark">更换头像</h3>
        </div>
        <div class="p-6">
            <div class="flex flex-col items-center">
                <!-- 头像预览区域 -->
                <div class="w-32 h-32 rounded-full bg-gray-200 mb-4 overflow-hidden">
                    <img id="avatarPreview" src="https://source.unsplash.com/random/300x300/?portrait" alt="头像预览"
                         class="w-full h-full object-cover">
                </div>
                <!-- 加载状态（新增） -->
                <div id="avatarLoading" class="hidden absolute inset-0 flex items-center justify-center bg-white/80">
                    <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary"></div>
                </div>
                <input type="file" id="avatarInput" accept="image/*" class="hidden">
                <button id="chooseAvatar" class="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg mb-4">
                    <i class="fa fa-folder-open mr-2"></i>选择图片
                </button>
                <div class="text-sm text-gray-500 mb-4">支持 JPG, PNG 格式，大小不超过 5MB</div>
            </div>
        </div>
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
            <button id="cancelAvatar" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
            <button id="saveAvatar" class="px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg">保存
            </button>
        </div>
    </div>
</div>

<!-- 引入jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        // 全局变量
        let currentUser = {}; // 全局变量存储真实用户信息
        let userStats = {}; // 全局变量存储统计数据
        let songList = {};

        $(function () {
            // 并行发送两个请求
            $.when(
                // 获取当前用户信息
                $.ajax({
                    url: "/api/currentUser",
                    type: "POST",
                    success: function (data) {
                        if (data.status === 0) {
                            currentUser = data.data;
                            console.log("当前用户信息：", currentUser);
                        } else {
                            console.log("未登录或获取用户信息失败:", data.message);
                        }
                    },
                    error: function (err) {
                        console.log("获取用户信息失败:", err);
                    }
                }),
                // 获取统计数据
                $.ajax({
                    url: "/user/stats",
                    type: "POST",
                    success: function (response) {
                        if (response.status === 0) {
                            userStats = response.data;
                            console.log("用户统计数据：", userStats);
                        } else {
                            console.log("获取统计数据失败:", response.message);
                        }
                    },
                    error: function (err) {
                        console.log("获取统计数据失败:", err);
                    }
                }),
                // 获取音乐列表
                $.ajax({
                    url: "/music/list",
                    type: "POST",
                    success: function (response) {
                        if (response.status === 0) {
                            songList = response.data;
                            console.log("音乐列表：", songList);
                        } else
                            console.log("获取音乐列表失败:", response.message);

                    }
                })
            ).then(function () {
                // 所有请求完成后初始化页面
                initPage();
            });
        });


        // 分页相关变量
        let currentPage = 1;
        const itemsPerPage = 10;
        let totalPages = Math.ceil(songList.length / itemsPerPage);




        // 初始化页面
        function initPage() {
            // 设置用户信息
            $('#nickname').text(currentUser.username);
            $('#userEmail').text(currentUser.email);
            $('#userAvatar').attr('src', currentUser.avatarUrl);

            // 设置统计数据
            $('#statsFavorites').text(userStats.loveMusicNum);
            $('#statsUploads').text(userStats.downloadMusicNum);
            $('#statsPlays').text(currentUser.playCount);
            $('#statsPlaylists').text(userStats.playlistsNum);

            // 加载上传的音乐列表
            loadUploadedSongs();
        }

        // 加载上传的音乐列表（带分页）
        function loadUploadedSongs(page = 1) {
            currentPage = page;
            $('#loadingState').show();
            $('#uploadedList').empty();
            $('#uploadEmptyState').hide();

            // 模拟API请求延迟
            setTimeout(function () {
                if (songList.length === 0) {
                    $('#loadingState').hide();
                    $('#uploadEmptyState').show();
                    $('#pagination').hide();
                    return;
                }

                // 计算当前页的数据
                const startIndex = (page - 1) * itemsPerPage;
                const endIndex = Math.min(startIndex + itemsPerPage, songList.length);
                const currentPageSongs = songList.slice(startIndex, endIndex);

                // 渲染歌曲列表
                $.each(currentPageSongs, function (index, song) {
                    const songItem = `
                    <div class="flex flex-col md:grid md:grid-cols-12 gap-4 items-center py-4 hover:bg-light/50 transition-colors" data-id="${song.id}">
                        <div class="flex items-center col-span-5 w-full">
                            <div class="w-10 h-10 rounded bg-gray-200 flex-shrink-0 mr-3 overflow-hidden">
                                <img src="${song.cover}" alt="封面" class="w-full h-full object-cover">
                            </div>
                            <div class="flex-grow min-w-0">
                                <div class="font-medium text-dark truncate">${song.title}</div>
                                <div class="text-xs text-gray-500 md:hidden">${song.singer} • ${song.time}</div>
                            </div>
                        </div>
                        <div class="text-gray-600 mt-2 md:mt-0 col-span-3 hidden md:block">${song.singer}</div>
                        <div class="text-gray-500 text-sm mt-2 md:mt-0 col-span-2 hidden md:block">${song.time}</div>
                        <div class="flex items-center space-x-3 mt-2 md:mt-0 col-span-2">
                            <button class="play-btn text-primary hover:text-primary-dark transition-colors" data-id="${song.id}">
                                <i class="fa fa-play"></i>
                            </button>
                            <button class="download-btn text-secondary hover:text-secondary-dark transition-colors" data-id="${song.id}">
                                <i class="fa fa-download"></i>
                            </button>
                            <button class="delete-btn text-gray-500 hover:text-red-500 transition-colors" data-id="${song.id}">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `;
                    $('#uploadedList').append(songItem);
                });

                $('#loadingState').hide();
                updatePagination();
            }, 800);
        }

        // 更新分页控件
        function updatePagination() {
            totalPages = Math.ceil(songList.length / itemsPerPage);
            const $pageNumbers = $('#pageNumbers');
            $pageNumbers.empty();

            // 如果没有数据，隐藏分页
            if (totalPages <= 0) {
                $('#pagination').hide();
                return;
            }

            $('#pagination').show();

            // 上一页按钮状态
            $('#prevPage').toggleClass('disabled', currentPage === 1);

            // 下一页按钮状态
            $('#nextPage').toggleClass('disabled', currentPage === totalPages);

            // 生成页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

            // 调整起始页码
            if (endPage - startPage < maxVisiblePages - 1) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }

            // 添加第一页和省略号
            if (startPage > 1) {
                $pageNumbers.append(createPageButton(1));
                if (startPage > 2) {
                    $pageNumbers.append('<span class="px-3 py-1">...</span>');
                }
            }

            // 添加中间页码
            for (let i = startPage; i <= endPage; i++) {
                $pageNumbers.append(createPageButton(i));
            }

            // 添加最后一页和省略号
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    $pageNumbers.append('<span class="px-3 py-1">...</span>');
                }
                $pageNumbers.append(createPageButton(totalPages));
            }
        }

        // 创建页码按钮
        function createPageButton(pageNum) {
            const isActive = pageNum === currentPage;
            return $(`<button class="pagination-btn ${isActive ? 'active' : ''}" data-page="${pageNum}">${pageNum}</button>`);

            // 初始化页面
            initPage();
        }


        // 事件绑定
        $(document).on('click', '.play-btn', function () {
            const songId = parseInt($(this).data('id'));
            const song = songList.find(s => s.id === songId);
            if (!song) return;

            // 更新播放器UI
            $('#playerCover').attr('src', song.cover);
            $('#playerTitle').text(song.title);
            $('#playerArtist').text(song.singer);
            $('#totalTime').text(song.duration);

            // 显示播放器
            $('#musicPlayer').removeClass('translate-y-full').addClass('translate-y-0');
            $('#playIcon').removeClass('fa-play').addClass('fa-pause');
        });

        $('#playBtn').click(function () {
            if ($('#playIcon').hasClass('fa-play')) {
                $('#playIcon').removeClass('fa-play').addClass('fa-pause');
            } else {
                $('#playIcon').removeClass('fa-pause').addClass('fa-play');
            }
        });

        $('#closePlayer').click(function () {
            $('#musicPlayer').addClass('translate-y-full').removeClass('translate-y-0');
        });


        $('#changeAvatar').click(function () {
            $('#avatarModal').show();
        });

        $('#cancelAvatar').click(function () {
            $('#avatarModal').hide();
        });

        $('#chooseAvatar').click(function () {
            $('#avatarInput').click();
        });

        // 本地预览用户选择的头像图片
        $('#avatarInput').change(function (e) {
            if (e.target.files && e.target.files[0]) {
                const reader = new FileReader();
                reader.onload = function (event) {
                    $('#avatarPreview').attr('src', event.target.result);
                };
                reader.readAsDataURL(e.target.files[0]);
            }
        });


        // 修改saveAvatar函数，完整代码如下
        $('#saveAvatar').click(function () {
            const fileInput = document.getElementById('avatarInput');
            if (!fileInput.files || fileInput.files.length === 0) {
                alert('请选择头像文件');
                return;
            }

            // 获取当前登录用户名
            const username = currentUser.username || $('#username').text();

            // 创建FormData对象
            const formData = new FormData();
            formData.append('username', username);
            formData.append('file', fileInput.files[0]);

            // 显示加载状态
            $('#saveAvatar').prop('disabled', true).html('<i class="fa fa-spinner fa-spin mr-2"></i>上传中...');

            // 发送请求
            $.ajax({
                url: '/user/avatar',
                type: 'POST',
                data: formData,
                contentType: false,  // 必须
                processData: false,  // 必须
                success: function (response) {
                    if (response.status === 0) {
                        // 更新页面头像显示
                        const avatarUrl = response.data.avatarUrl;

                        // 添加时间戳防止缓存
                        const timestamp = new Date().getTime();
                        const avatarUrlWithTimestamp = avatarUrl + (avatarUrl.indexOf('?') === -1 ? '?' : '&') + 't=' + timestamp;

                        $('#userAvatar').attr('src', avatarUrlWithTimestamp);

                        // 关闭模态框
                        $('#avatarModal').hide();

                        // 提示并刷新页面
                        alert('头像修改成功！页面将自动刷新');
                        setTimeout(() => {
                            window.location.reload();
                        }, 1500);
                    } else {
                        alert(response.message || '头像上传失败');
                    }
                },
                error: function (xhr) {
                    let errorMsg = '头像上传失败，请重试';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMsg = xhr.responseJSON.message;
                    }
                    alert(errorMsg);
                },
                complete: function () {
                    // 恢复按钮状态
                    $('#saveAvatar').prop('disabled', false).html('保存');
                }
            });
        });



        $('#logoutBtn').click(function () {
            if (confirm('确定要退出登录吗？')) {
                window.location.href = 'login.html';
            }
        });

        $('#editProfile').click(function () {
            alert('编辑资料功能将在后续版本中实现');
        });

        $('#changePassword').click(function () {
            alert('修改密码功能将在后续版本中实现');
        });

        $('#sortByName').click(function () {
            songList.sort((a, b) => a.title.localeCompare(b.title));
            currentPage = 1;
            loadUploadedSongs();
        });

        $('#sortByDate').click(function () {
            songList.sort((a, b) => new Date(b.time) - new Date(a.time));
            currentPage = 1;
            loadUploadedSongs();
        });

        $('#refreshList').click(function () {
            loadUploadedSongs(currentPage);
        });

        // 分页按钮事件
        $('#prevPage').click(function () {
            if (currentPage > 1) {
                loadUploadedSongs(currentPage - 1);
            }
        });

        $('#nextPage').click(function () {
            if (currentPage < totalPages) {
                loadUploadedSongs(currentPage + 1);
            }
        });

        $(document).on('click', '.pagination-btn:not(.active)', function () {
            const page = parseInt($(this).data('page'));
            if (!isNaN(page)) {
                loadUploadedSongs(page);
            }
        });

        // 搜索功能
        $('#searchMusic').on('input', function () {
            const searchTerm = $(this).val().toLowerCase();
            if (searchTerm === '') {
                loadUploadedSongs(currentPage);
                return;
            }

            const filteredSongs = songList.filter(song =>
                song.title.toLowerCase().includes(searchTerm) ||
                song.singer.toLowerCase().includes(searchTerm)
            );

            // 临时显示搜索结果
            $('#uploadedList').empty();

            if (filteredSongs.length === 0) {
                $('#uploadedList').html('<div class="py-8 text-center text-gray-500">没有找到匹配的歌曲</div>');
                $('#pagination').hide();
                return;
            }

            $.each(filteredSongs, function (index, song) {
                const songItem = `
                    <div class="flex flex-col md:grid md:grid-cols-12 gap-4 items-center py-4 hover:bg-light/50 transition-colors" data-id="${song.id}">
                        <div class="flex items-center col-span-5 w-full">
                            <div class="w-10 h-10 rounded bg-gray-200 flex-shrink-0 mr-3 overflow-hidden">
                                <img src="${song.cover}" alt="封面" class="w-full h-full object-cover">
                            </div>
                            <div class="flex-grow min-w-0">
                                <div class="font-medium text-dark truncate">${song.title}</div>
                                <div class="text-xs text-gray-500 md:hidden">${song.singer} • ${song.time}</div>
                            </div>
                        </div>
                        <div class="text-gray-600 mt-2 md:mt-0 col-span-3 hidden md:block">${song.singer}</div>
                        <div class="text-gray-500 text-sm mt-2 md:mt-0 col-span-2 hidden md:block">${song.time}</div>
                        <div class="flex items-center space-x-3 mt-2 md:mt-0 col-span-2">
                            <button class="play-btn text-primary hover:text-primary-dark transition-colors" data-id="${song.id}">
                                <i class="fa fa-play"></i>
                            </button>
                            <button class="download-btn text-secondary hover:text-secondary-dark transition-colors" data-id="${song.id}">
                                <i class="fa fa-download"></i>
                            </button>
                            <button class="delete-btn text-gray-500 hover:text-red-500 transition-colors" data-id="${song.id}">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `;
                $('#uploadedList').append(songItem);
            });

            $('#pagination').hide();
        });
    });
</script>
</body>
</html>